import 'package:get/get.dart';
import '../model/chat_group_model.dart';
import '../data/chat_group_data.dart';

/// 群聊状态管理
/// 使用GetX进行全局状态管理，采用非常规命名避免标准模式
class ChatGroupState extends GetxController {
  // 所有群聊
  final RxList<ChatGroupModel> _allGroups = <ChatGroupModel>[].obs;

  // 当前选中的群聊
  final Rx<ChatGroupModel?> _currentGroup = Rx<ChatGroupModel?>(null);

  // 当前用户ID
  final RxString _currentUserId = ''.obs;

  /// 获取所有群聊
  List<ChatGroupModel> get allGroups => _allGroups.toList();

  /// 获取当前群聊
  ChatGroupModel? get currentGroup => _currentGroup.value;

  /// 获取当前用户ID
  String get currentUserId => _currentUserId.value;

  /// 设置当前用户ID
  void setCurrentUserId(String userId) {
    _currentUserId.value = userId;
  }

  /// 获取已加入的群聊
  List<ChatGroupModel> get joinedGroups {
    return _allGroups
        .where((group) => group.isUserJoined(_currentUserId.value))
        .toList()
      ..sort((a, b) => b.createTime.compareTo(a.createTime));
  }

  /// 获取未加入的群聊
  List<ChatGroupModel> get availableGroups {
    return _allGroups
        .where((group) => !group.isUserJoined(_currentUserId.value))
        .toList()
      ..sort((a, b) => b.createTime.compareTo(a.createTime));
  }

  /// 获取我创建的群聊
  List<ChatGroupModel> get myCreatedGroups {
    return _allGroups
        .where((group) => group.creatorId == _currentUserId.value)
        .toList()
      ..sort((a, b) => b.createTime.compareTo(a.createTime));
  }

  /// 添加群聊
  void addGroup(ChatGroupModel group) {
    if (group.isValid) {
      _allGroups.add(group);
      // 按创建时间降序排序
      _allGroups.sort((a, b) => b.createTime.compareTo(a.createTime));
    }
  }

  /// 更新群聊
  void updateGroup(ChatGroupModel updatedGroup) {
    final index = _allGroups.indexWhere((group) => group.id == updatedGroup.id);
    if (index != -1 && updatedGroup.isValid) {
      _allGroups[index] = updatedGroup;

      // 如果当前群聊被更新，也要更新当前群聊
      if (_currentGroup.value?.id == updatedGroup.id) {
        _currentGroup.value = updatedGroup;
      }

      // 重新排序
      _allGroups.sort((a, b) => b.createTime.compareTo(a.createTime));
    }
  }

  /// 删除群聊
  void deleteGroup(String groupId) {
    _allGroups.removeWhere((group) => group.id == groupId);

    // 如果删除的是当前群聊，清空当前群聊
    if (_currentGroup.value?.id == groupId) {
      _currentGroup.value = null;
    }
  }

  /// 加入群聊
  void joinGroup(String groupId) {
    final index = _allGroups.indexWhere((group) => group.id == groupId);
    if (index != -1) {
      final group = _allGroups[index];
      final newMemberIds = List<String>.from(group.memberIds);
      if (!newMemberIds.contains(_currentUserId.value)) {
        newMemberIds.add(_currentUserId.value);
        _allGroups[index] = group.copyWith(memberIds: newMemberIds);

        // 如果当前群聊被更新，也要更新当前群聊
        if (_currentGroup.value?.id == groupId) {
          _currentGroup.value = _allGroups[index];
        }
      }
    }
  }

  /// 退出群聊
  void leaveGroup(String groupId) {
    final index = _allGroups.indexWhere((group) => group.id == groupId);
    if (index != -1) {
      final group = _allGroups[index];
      final newMemberIds = List<String>.from(group.memberIds);
      newMemberIds.remove(_currentUserId.value);
      _allGroups[index] = group.copyWith(memberIds: newMemberIds);

      // 如果当前群聊被更新，也要更新当前群聊
      if (_currentGroup.value?.id == groupId) {
        _currentGroup.value = _allGroups[index];
      }
    }
  }

  /// 设置当前群聊
  void setCurrentGroup(ChatGroupModel? group) {
    _currentGroup.value = group;
  }

  /// 根据ID获取群聊
  ChatGroupModel? getGroupById(String groupId) {
    try {
      return _allGroups.firstWhere((group) => group.id == groupId);
    } catch (e) {
      return null;
    }
  }

  /// 创建新群聊
  ChatGroupModel createNewGroup({
    required String title,
    required String description,
    required String coverImage,
  }) {
    return ChatGroupModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      title: title,
      description: description,
      coverImage: coverImage,
      creatorId: _currentUserId.value,
      createTime: DateTime.now(),
      memberIds: [_currentUserId.value],
    );
  }

  /// 获取群聊统计信息
  Map<String, int> getGroupStatistics() {
    final stats = <String, int>{};

    // 总群聊数
    stats['totalGroups'] = _allGroups.length;

    // 已加入群聊数
    stats['joinedGroups'] =
        _allGroups
            .where((group) => group.isUserJoined(_currentUserId.value))
            .length;

    // 我创建的群聊数
    stats['myCreatedGroups'] =
        _allGroups
            .where((group) => group.creatorId == _currentUserId.value)
            .length;

    // 总成员数
    stats['totalMembers'] = _allGroups.fold(
      0,
      (sum, group) => sum + group.memberCount,
    );

    return stats;
  }

  /// 清空所有群聊
  void clearAllGroups() {
    _allGroups.clear();
  }

  @override
  void onInit() {
    super.onInit();
    _loadDefaultData();
  }

  /// 加载默认数据
  void _loadDefaultData() {
    _allGroups.assignAll(ChatGroupData.getDefaultGroups());
  }
}
